/*
 * @Author: 明月下
 * @Date: 2022-07-30 17:37:06
 * @LastEditors: 明月下
 * @LastEditTime: 2022-08-31 01:07:56
 * @FilePath: \ali-yun-slimming\express\config\mongoDbConnection.js
 * @Description: 连接到mongodb数据库，返回的是链接到collection的方法
 */
const MongoClient = require("mongodb").MongoClient;

const user = 'slimming'
const password = 'qeqewsad'
const dbName = "slimming";
const url = `mongodb://${user}:${password}@localhost:27017/${dbName}`;

let _db = null;

// 连接数据库的函数，_db没有数据库对象时就会进行连接并返回_db对象
async function connectDb() {
    if (!_db) {
        const client = new MongoClient(url, { useUnifiedTopology: true });
        try {
            await client.connect();
            _db = await client.db(dbName);
        } catch (error) {
            console.error(error)
            throw "连接到数据库出错";
        }
    }
    return _db;
}

exports.getCollection = (collection) => {
    let _col = null;
    return async() => {
        if(!_col) {
            try {
                const db = await connectDb();
                _col = await db.collection(collection);
            } catch (error) {
                console.error(error)
                throw "选择collection出错";
            }
        }
        return _col;
    }
}